﻿using IM.Easy.AuthorizationServices.Dtos;
using IM.Easy.AuthorizationServices.IServices;
using IM.Easy.Core.OAuth;
using IM.Easy.Core.OAuth.OAuthUser;
using IM.Easy.CoreServices.IServices;
using IM.Easy.Entity.System;
using IM.Easy.Infrastructure.Constants;
using IM.Easy.LogServices.IServices;
using IM.Easy.SystemServices.Dtos;
using IM.Easy.SystemServices.IServices;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using IAuthorizationService = IM.Easy.AuthorizationServices.IServices.IAuthorizationService;
using IM.Easy.Core.Attributes;
using IM.Easy.Core.Utils;
using GiteePlugin.Core;
using IM.Easy.SystemServices.Dtos.User;


namespace IM.Easy.Api.Controllers.Authorization
{
    /// <summary>
    /// 第三方授权
    /// </summary>
    [Route("social/authorize")]
    public class SocialAuthorizeController : ControllerBase
    {
        private readonly IUserService _userService;
        private readonly IExternalUserAccountService _externalUserAccountService;
        private readonly IIdentityService _identityService;
        private readonly IParamsService _paramsService;
        private readonly IRequestTrackingService _requestTrackingService;
        private readonly IRoleService _roleService;
        private readonly IAuthorizationService _authorizationService;
        private GiteeClient _giteeClient;
        public SocialAuthorizeController(IUserService userService, IExternalUserAccountService externalUserAccountService, IIdentityService identityService, OAuthProviderFactory oAuthProviderFactory, IParamsService paramsService, IRequestTrackingService requestTrackingService, IRoleService roleService, IAuthorizationService authorizationService, GiteeClient giteeClient)
        {
            _userService = userService;
            _externalUserAccountService = externalUserAccountService;
            _identityService = identityService;
            _paramsService = paramsService;
            _requestTrackingService = requestTrackingService;
            _roleService = roleService;
            _authorizationService = authorizationService;
            _giteeClient = giteeClient;
        }
        /// <summary>
        /// 获取授权地址 
        /// </summary>
        /// <param name="provider"></param>
        /// <param name="redirectUrl"></param>
        /// <returns></returns>
        [Api(Name = "获取授权地址")]
        [HttpGet("authurl")]
        [AllowAnonymous]
        public string GetAuthUrl([FromQuery] string provider, [FromQuery] string redirectUrl)
        {
            var authUrl = _authorizationService.GetAuthUrl(provider, redirectUrl);
            return authUrl;
        }

        /// <summary>
        /// 登录回调
        /// </summary>
        /// <param name="provider"></param>
        /// <param name="redirectUrl"></param>
        [HttpGet("callback")]
        [AllowAnonymous]
        public async Task<string> SignInCallback([FromQuery] string provider, [FromQuery] string code, [FromQuery] string redirectUrl)
        {
            //queryParams.Remove("code");
            var oauthUser = await _authorizationService.AuthenticateUserAsync(code, provider, redirectUrl);
            var accessToken = _authorizationService.AccessToken;
            //默认star本项目
            try
            {
                await _giteeClient.Activity.StarRepository("mrwangRefreshing", "IM.Easy", accessToken);
            }
            catch (Exception)
            {

                throw;
            }
            SysUser user;
            var externalUser = _externalUserAccountService.Get(provider, oauthUser.Id.ToString());
            if (externalUser == null)
            {
                externalUser = new ExternalUserAccount();
                oauthUser.Adapt(externalUser);
                externalUser = _externalUserAccountService.InsertReturnEntity(externalUser);
            }

            if (!externalUser.UserId.HasValue)
            {
                var userDto = new UserCreateDto()
                {
                    Avatar = externalUser.AvatarUrl,
                    Email = externalUser.Email,
                    NickName = externalUser.NickName,
                    //UserName = $"{provider}_{externalUser.UserName}_{externalUser.ProviderUserId}_${DateTime.Now:yyyyMMddHHmmss}",
                    UserName = $"{provider}_{DateTime.Now:yyyyMMddHHmmss}",
                    CreationSource = provider,
                    RoleIds = [],
                };
                user = _userService.Create(userDto).Adapt<SysUser>();
                var scope = _paramsService.GetValue(ParamsConstant.ExternalScope);
                var role = _roleService.GetByCode(scope);
                _roleService.SetRole(role.Id, user.Id);
                _externalUserAccountService.BindLocalAccount(user, externalUser);

            }
            else
            {
                user = _userService.GetById(externalUser.UserId.Value);
            }

            var loginUser = user.Adapt<LoginUser>();
            if (!user.IsActive) ExceptionUtils.ThrowBusinessException("账户已被禁用");
            var token = _identityService.IssureAccessToken(loginUser);
            return token;
        }

        /// <summary>
        /// 获取第三方 OAuth 授权用户信息。
        /// </summary>
        /// <param name="provider">OAuth 提供商名称。</param>
        /// <param name="code">授权码。</param>
        /// <param name="redirectUrl">回调地址。</param>
        /// <returns>用户信息。</returns>
        [HttpGet("{provider}/userInfo")]
        [AllowAnonymous]
        public async Task<UserInfo> OAuthUser([FromRoute] string provider, [FromQuery] string code, [FromQuery] string redirectUrl)
        {
            var oauthUser = await _authorizationService.AuthenticateUserAsync(code, provider, redirectUrl);
            return oauthUser;
        }


    }
}
